<template>
  <div>
    <h2>仓库管理</h2>
    <el-table :data="warehouses" stripe style="width: 100%">
      <el-table-column prop="companyName" label="公司名称" />
      <el-table-column prop="totalItems" label="货物总数" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="mini" @click="handleEntry(scope.row.companyId, 10)">入库 10 件</el-button>
          <el-button size="mini" type="danger" @click="handleExit(scope.row.companyId, 10)">出库 10 件</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      warehouses: [] // 存储所有仓库信息
    };
  },
  created() {
    this.fetchWarehouses(); // 初始化获取仓库信息
  },
  methods: {
    // 获取所有仓库信息
    async fetchWarehouses() {
      try {
        const response = await axios.get('http://localhost:8080/warehouse/all');
        this.warehouses = await Promise.all(
            response.data.map(async warehouse => {
              const companyResponse = await axios.get(`http://localhost:8080/company/${warehouse.companyId}`);
              return {
                ...warehouse,
                companyName: companyResponse.data.companyName
              };
            })
        );
      } catch (error) {
        console.error('Failed to fetch warehouses:', error);
      }
    },
    // 处理入库操作
    async handleEntry(companyId, totalItems) {
      try {
        await axios.post('http://localhost:8080/warehouse/entry', null, {
          params: {
            companyId: companyId,
            totalItems: totalItems
          }
        });
        this.fetchWarehouses(); // 更新完成后重新获取仓库信息
      } catch (error) {
        console.error('Failed to update warehouse for entry:', error);
      }
    },
    // 处理出库操作
    async handleExit(companyId, totalItems) {
      try {
        await axios.post('http://localhost:8080/warehouse/exit', null, {
          params: {
            companyId: companyId,
            totalItems: totalItems
          }
        });
        this.fetchWarehouses(); // 更新完成后重新获取仓库信息
      } catch (error) {
        console.error('Failed to update warehouse for exit:', error);
      }
    }
  }
};
</script>

<style scoped>
h2 {
  margin-bottom: 20px;
}
</style>
